package top.hudk.sql.strategy;

import lombok.extern.slf4j.Slf4j;
import top.hudk.sql.domin.ShardingResult;
import top.hudk.sql.strategy.abstracts.HashShardingStrategy;

/**
 * 请输入描述信息
 *
 * @author HuDongkang
 * @date 2022/9/1 16:05
 */
@Slf4j
public class DefaultHashShardingStrategy extends HashShardingStrategy {
    /**
     * 分库分表策略
     *
     * @param shardingValue   分表字段的值
     * @param dbTotalCount    数据库个数
     * @param tableTotalCount 表个数
     * @return 分库分表结果
     */
    @Override
    public ShardingResult sharding(Object shardingValue, int dbTotalCount, int tableTotalCount) {
        if (shardingValue == null) {
            throw new IllegalArgumentException("invalid shardingColumnValue");
        } else if (dbTotalCount <= 0) {
            throw new IllegalArgumentException("invalid dbTotalCount:" + dbTotalCount);
        } else if (tableTotalCount <= 0) {
            throw new IllegalArgumentException("invalid tableTotalCount:" + tableTotalCount);
        } else if (tableTotalCount < dbTotalCount) {
            throw new IllegalArgumentException("tableTotalCount[" + tableTotalCount + "] can't less than dbTotalCount[" + dbTotalCount + "]");
        } else {
            int hash = shardingValue.toString().hashCode();
            if (hash < 0) {
                hash = Math.abs(hash);
            }

            int tableNo = hash % tableTotalCount;
            int dbNo = tableNo / (tableTotalCount / dbTotalCount);
            String tableKey = String.format("%04d", tableNo);
            String dbKey = String.format("%02d", dbNo);
            return new ShardingResult(dbKey, tableKey);
        }
    }
}
